package com.ytjj.common.utils;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.ytjj.common.constants.*;
import com.ytjj.common.model.YxAlipayConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Description 支付宝支付工具类
 *
 * @Version 1.0
 * 
 */
@Slf4j
@Service
public class AlipayUtil {
    @Resource
    private AlipayConstants alipayConstants;
    @Resource
    private AlipayConstantsOld alipayConstantsOld;
    @Resource
    private AlipayCertConstants alipayCertConstants;
    @Resource
    private AlipayConstants05 alipayConstants05;

    private static final String GATEWAY_URL ="https://openapi.alipay.com/gateway.do";
    private static final String FORMAT ="json";
    private static final String CHARSET = "UTF-8";

    public AlipayClient getAlipayClientByMysql(YxAlipayConfig yxAlipayConfig){
        AlipayClient alipayClient = new DefaultAlipayClient
                (GATEWAY_URL,
                        yxAlipayConfig.getAppid(),
                        yxAlipayConfig.getRsaPrivateKey(),
                        alipayConstants.getFORMAT(),
                        CHARSET,
                        yxAlipayConfig.getAlipayPublicKey(),
                        yxAlipayConfig.getSignType());
        return alipayClient;
    }

    public AlipayClient getAlipayClient(String childId) {
        // 向支付宝发送支付请求
        // 1. 封装RSA签名方式
        //获得初始化的AlipayClient
        AlipayClient alipayClient;
        //代表的是app支付
        if (StringUtils.isNotBlank(childId) && childId.equals("APP_1")) {
            alipayClient = new DefaultAlipayClient
                    (alipayConstants.getGATEWAY_URL(),
                            alipayConstants.getAPP_APPID(),
                            alipayConstants.getAPP_RSA_PRIVATE_KEY(),
                            alipayConstants.getFORMAT(),
                            alipayConstants.getCHARSET(),
                            alipayConstants.getAPP_ALIPAY_PUBLIC_KEY(),
                            alipayConstants.getSIGNTYPE());
            log.info("APP_1");
        } else {
            alipayClient = new DefaultAlipayClient
                    (alipayConstants.getGATEWAY_URL(),
                            alipayConstants.getAPPID(),
                            alipayConstants.getRSA_PRIVATE_KEY(),
                            alipayConstants.getFORMAT(),
                            alipayConstants.getCHARSET(),
                            alipayConstants.getALIPAY_PUBLIC_KEY(),
                            alipayConstants.getSIGNTYPE());
            log.info("非app");
        }
        return alipayClient;
    }

    public AlipayClient getAlipayClientOld(String childId) {
        // 向支付宝发送支付请求
        // 1. 封装RSA签名方式
        //获得初始化的AlipayClient
        AlipayClient alipayClient;
        if (StringUtils.isNotBlank(childId) && childId.equals("APP_1")) {
            alipayClient = new DefaultAlipayClient
                    (alipayConstants.getGATEWAY_URL(),
                            alipayConstants.getAPP_APPID(),
                            alipayConstants.getAPP_RSA_PRIVATE_KEY(),
                            alipayConstants.getFORMAT(),
                            alipayConstants.getCHARSET(),
                            alipayConstants.getAPP_ALIPAY_PUBLIC_KEY(),
                            alipayConstants.getSIGNTYPE());
        } else {
             alipayClient = new DefaultAlipayClient
                    (alipayConstantsOld.getGATEWAY_URL(),
                            alipayConstantsOld.getAPPID(),
                            alipayConstantsOld.getRSA_PRIVATE_KEY(),
                            alipayConstantsOld.getFORMAT(),
                            alipayConstantsOld.getCHARSET(),
                            alipayConstantsOld.getALIPAY_PUBLIC_KEY(),
                            alipayConstantsOld.getSIGNTYPE());
        }

        return alipayClient;
    }

    public AlipayClient getAlipayClient05() {
        // 向支付宝发送支付请求
        // 1. 封装RSA签名方式
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient
                (alipayConstants05.getGATEWAY_URL(),
                        alipayConstants05.getAPPID(),
                        alipayConstants05.getRSA_PRIVATE_KEY(),
                        alipayConstants05.getFORMAT(),
                        alipayConstants05.getCHARSET(),
                        alipayConstants05.getALIPAY_PUBLIC_KEY(),
                        alipayConstants05.getSIGNTYPE());
        return alipayClient;
    }

//    public AlipayClient getAlipayClient04() {
//        // 向支付宝发送支付请求
//        // 1. 封装RSA签名方式
//        //获得初始化的AlipayClient
//        AlipayClient alipayClient = new DefaultAlipayClient
//                (alipayConstants04.getGATEWAY_URL(),
//                        alipayConstants04.getAPPID(),
//                        alipayConstants04.getRSA_PRIVATE_KEY(),
//                        alipayConstants04.getFORMAT(),
//                        alipayConstants04.getCHARSET(),
//                        alipayConstants04.getALIPAY_PUBLIC_KEY(),
//                        alipayConstants04.getSIGNTYPE());
//        return alipayClient;
//    }

    public AlipayClient getAlipayClientByCert() {
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");  //gateway:支付宝网关（固定）https://openapi.alipay.com/gateway.do
        certAlipayRequest.setAppId(alipayCertConstants.getAPPID());  //APPID 即创建应用后生成,详情见创建应用并获取 APPID
        certAlipayRequest.setPrivateKey(alipayCertConstants.getRSA_PRIVATE_KEY());  //开发者应用私钥，由开发者自己生成
        certAlipayRequest.setFormat("json");  //参数返回格式，只支持 json 格式
        certAlipayRequest.setCharset("UTF8");  //请求和签名使用的字符编码格式，支持 GBK和 UTF-8
        certAlipayRequest.setSignType(alipayConstants.getSIGNTYPE());  //商户生成签名字符串所使用的签名算法类型，目前支持 RSA2 和 RSA，推荐商家使用 RSA2。
        certAlipayRequest.setCertPath(alipayCertConstants.getAPP_CERT_PATH()); //应用公钥证书路径（app_cert_path 文件绝对路径）
        certAlipayRequest.setAlipayPublicCertPath(alipayCertConstants.getALIPAY_CERT_PATH()); //支付宝公钥证书文件路径（alipay_cert_path 文件绝对路径）
        certAlipayRequest.setRootCertPath(alipayCertConstants.getALIPAY_ROOT_CERT_PATH());  //支付宝CA根证书文件路径（alipay_root_cert_path 文件绝对路径）

        AlipayClient alipayClient = null;
        try {
            alipayClient = new DefaultAlipayClient(certAlipayRequest);
        } catch (AlipayApiException e) {
            log.info("===初始化支付宝客户端异常==={}", e);
        }
        return alipayClient;
    }

    /**
     * 支付宝小程序客户端
     * @return
     */
    public AlipayClient getJsApiAliPayClient(String childId) {

        AlipayClient alipayClient ;
        if (StringUtils.isNotBlank(childId) && "1".equals(childId)) {
            alipayClient = new DefaultAlipayClient
                    (alipayConstants.getGATEWAY_URL(),
                            alipayConstants.getCHILD_JSAPI_APPID(),
                            alipayConstants.getCHILD_JSAPI_RSA_PRIVATE_KEY(),
                            alipayConstants.getFORMAT(),
                            alipayConstants.getCHARSET(),
                            alipayConstants.getCHILD_JSAPI_ALIPAY_PUBLIC_KEY(),
                            alipayConstants.getSIGNTYPE());

        } else {
            alipayClient = new DefaultAlipayClient
                    (alipayConstants.getGATEWAY_URL(),
                            alipayConstants.getJSAPI_APPID(),
                            alipayConstants.getJSAPI_RSA_PRIVATE_KEY(),
                            alipayConstants.getFORMAT(),
                            alipayConstants.getCHARSET(),
                            alipayConstants.getJSAPI_ALIPAY_PUBLIC_KEY(),
                            alipayConstants.getSIGNTYPE());
        }

        return alipayClient;
    }


    /**
     * 将request中的参数转换成Map
     */
    public static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }

        return retMap;
    }
}
